import { type FC, useMemo, memo } from 'react';
import { View } from 'react-native';
import { useMemoizedFn } from 'ahooks';
import PreviewItem from './item';
import { openZoomViewer } from '../ZoomViewer';
import type { PreviewContentProps } from './types';
import styles from './styles';

const PreviewContent: FC<PreviewContentProps> = (props) => {
  const {
    width,
    urls = [],
    space = 4,
    cols = 3
  } = props;

  const maxRow = Math.ceil(urls.length / cols);

  const size = useMemo(() => {
    return (width / cols) - ((cols - 1) * space) / cols;
  }, [width, cols, space, urls]);

  const onPress = useMemoizedFn((index: number) => {
    const _urls = urls.map(e => e.src);
    openZoomViewer({ urls: _urls, index });
  });

  return (
    <View style={styles.images}>
      {urls.map((item, i) => {
        const lastCol = !((i + 1) % cols);
        const row = Math.ceil((i + 1) / cols);
        const lastRow = row === maxRow;
        return (
          <PreviewItem
            key={i}
            index={i}
            item={item}
            size={size}
            space={space}
            lastCol={lastCol}
            lastRow={lastRow}
            onPress={onPress}
          />
        );
      })}
    </View>
  );
}

export default memo(PreviewContent);